import 'package:flutter/foundation.dart';
import 'package:meco/common/models/chat_room_model.dart';
import 'package:meco/common/data/services/database_service.dart';

class ChatRoomRepository {
  final DatabaseService _databaseService = DatabaseService();
  final String _tableName = 'chat_rooms';

  // 创建聊天室
  Future<int> createChatRoom(ChatRoom chatRoom) async {
    final db = await _databaseService.database;
    try {
      return await db.insert(_tableName, chatRoom.toJson());
    } catch (e) {
      debugPrint('创建聊天室失败: $e');
      return -1;
    }
  }

  // 获取聊天室详情
  Future<ChatRoom?> getChatRoomById(int id) async {
    final db = await _databaseService.database;
    try {
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        where: 'id = ?',
        whereArgs: [id],
      );

      if (maps.isEmpty) {
        return null;
      }

      return ChatRoom.fromJson(maps.first);
    } catch (e) {
      debugPrint('获取聊天室详情失败: $e');
      return null;
    }
  }

  // 更新聊天室信息
  Future<bool> updateChatRoom(ChatRoom chatRoom) async {
    if (chatRoom.id == null) {
      return false;
    }

    final db = await _databaseService.database;
    try {
      final result = await db.update(
        _tableName,
        chatRoom.toJson(),
        where: 'id = ?',
        whereArgs: [chatRoom.id],
      );
      return result > 0;
    } catch (e) {
      debugPrint('更新聊天室失败: $e');
      return false;
    }
  }

  // 删除聊天室
  Future<bool> deleteChatRoom(int id) async {
    final db = await _databaseService.database;
    try {
      final result = await db.delete(
        _tableName,
        where: 'id = ?',
        whereArgs: [id],
      );
      return result > 0;
    } catch (e) {
      debugPrint('删除聊天室失败: $e');
      return false;
    }
  }

  // 获取用户参与的所有聊天室
  Future<List<ChatRoom>> getChatRoomsByUserId(int userId) async {
    final db = await _databaseService.database;
    try {
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        orderBy: 'last_message_time DESC, updated_at DESC',
      );

      if (maps.isEmpty) {
        return [];
      }

      // 过滤出用户参与的聊天室
      return maps
          .map((map) => ChatRoom.fromJson(map))
          .where((room) => room.memberIds.contains(userId))
          .toList();
    } catch (e) {
      debugPrint('获取用户聊天室列表失败: $e');
      return [];
    }
  }

  // 更新聊天室最后一条消息
  Future<bool> updateLastMessage(
    int chatRoomId,
    String message,
    DateTime messageTime,
  ) async {
    final db = await _databaseService.database;
    try {
      debugPrint('正在更新聊天室 $chatRoomId 的最后一条消息: $message');

      final result = await db.update(
        _tableName,
        {
          'last_message': message,
          'last_message_time': messageTime.millisecondsSinceEpoch,
          'updated_at': DateTime.now().millisecondsSinceEpoch,
        },
        where: 'id = ?',
        whereArgs: [chatRoomId],
      );

      debugPrint('更新聊天室最后一条消息结果: ${result > 0 ? '成功' : '失败'}');
      return result > 0;
    } catch (e) {
      debugPrint('更新最后一条消息失败: $e');
      return false;
    }
  }

  // 获取聊天室未读消息数
  Future<int> getUnreadMessagesCount(int chatRoomId, int userId) async {
    final db = await _databaseService.database;
    try {
      // 查询不包含当前用户ID在已读列表中的消息
      final result = await db.rawQuery(
        '''
        SELECT COUNT(*) as count 
        FROM chat_messages 
        WHERE chat_room_id = ? 
        AND sender_id != ? 
        AND (read_by IS NULL OR read_by NOT LIKE '%$userId%')
      ''',
        [chatRoomId, userId],
      );

      if (result.isNotEmpty) {
        return result.first['count'] as int;
      }
      return 0;
    } catch (e) {
      debugPrint('获取未读消息数失败: $e');
      return 0;
    }
  }

  // 检查聊天室是否存在
  Future<bool> isChatRoomExist(List<int> memberIds, bool isGroup) async {
    // 对于单聊，检查是否已存在包含这两个用户的聊天室
    if (!isGroup && memberIds.length == 2) {
      final db = await _databaseService.database;
      final rooms = await db.query(_tableName, where: 'is_group = 0');

      for (var room in rooms) {
        final chatRoom = ChatRoom.fromJson(room);
        if (chatRoom.memberIds.length == 2 &&
            chatRoom.memberIds.contains(memberIds[0]) &&
            chatRoom.memberIds.contains(memberIds[1])) {
          return true;
        }
      }
    }
    return false;
  }

  // 查找两个用户之间的私聊聊天室
  Future<ChatRoom?> findPrivateChatRoom(int userId1, int userId2) async {
    final db = await _databaseService.database;
    try {
      final rooms = await db.query(_tableName, where: 'is_group = 0');

      for (var room in rooms) {
        final chatRoom = ChatRoom.fromJson(room);
        if (chatRoom.memberIds.length == 2 &&
            chatRoom.memberIds.contains(userId1) &&
            chatRoom.memberIds.contains(userId2)) {
          return chatRoom;
        }
      }
      return null;
    } catch (e) {
      debugPrint('查找私聊聊天室失败: $e');
      return null;
    }
  }

  // 获取用户参与的群聊数量
  Future<int> getGroupChatCount(int userId) async {
    final db = await _databaseService.database;
    try {
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        where: 'is_group = ?',
        whereArgs: [1],
      );

      if (maps.isEmpty) {
        return 0;
      }

      // 过滤出用户参与的群聊
      final groupChats =
          maps
              .map((map) => ChatRoom.fromJson(map))
              .where((room) => room.memberIds.contains(userId))
              .toList();

      return groupChats.length;
    } catch (e) {
      debugPrint('获取用户群聊数量失败: $e');
      return 0;
    }
  }

  // 获取用户参与的单聊数量
  Future<int> getPrivateChatCount(int userId) async {
    final db = await _databaseService.database;
    try {
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        where: 'is_group = ?',
        whereArgs: [0],
      );

      if (maps.isEmpty) {
        return 0;
      }

      // 过滤出用户参与的单聊
      final privateChats =
          maps
              .map((map) => ChatRoom.fromJson(map))
              .where((room) => room.memberIds.contains(userId))
              .toList();

      return privateChats.length;
    } catch (e) {
      debugPrint('获取用户单聊数量失败: $e');
      return 0;
    }
  }
}
